package timbap.visualizer.impl.context.playlist;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import timbap.visualizer.api.context.playlist.AbstractPlaylistManager;
import timbap.visualizer.api.exceptions.PlaylistParserException;
import timbap.visualizer.api.model.PlaylistEntry;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class M3UPlaylistManagerImpl extends AbstractPlaylistManager {

	private static final Log LOG = LogFactory.getLog(M3UPlaylistManagerImpl.class);

    private static File resolveToFile(File pReferenceDirectory, String pFileReference) {
    	File tAudioFile = new File(pFileReference);
    	if (!tAudioFile.isAbsolute() && !tAudioFile.getPath().startsWith("\\")) {
    		tAudioFile = new File(pReferenceDirectory, pFileReference);
    	}
    	if (!tAudioFile.exists()) {
        	try {
				URI tUri = new URI(pFileReference);
				if (tUri.getScheme() != null && tUri.getScheme().equals("file")) {
					if (tUri.getAuthority() != null) {
		    			tUri = new URI(tUri.getScheme() + ":" + tUri.getRawPath());
		    		}
		    		tAudioFile = new File(tUri);
				}
	    	} catch (URISyntaxException e) {
				LOG.warn("File reference " + pFileReference + " could not be resolved to a path or local file URI");
			}
    		
    	}
    	return tAudioFile;
    }

	
    @Override
    public List<PlaylistEntry> parsePlaylist(File pPlaylistFile)
                throws IOException, PlaylistParserException {
        
    	setPlaylistName(pPlaylistFile.getName());
        List<PlaylistEntry> tPlaylist = new ArrayList<PlaylistEntry>();
        LineNumberReader tLineNumberReader = 
            new LineNumberReader(new FileReader(pPlaylistFile));
        
        String tCurrentLine;
        while ((tCurrentLine = tLineNumberReader.readLine()) != null) {
            PlaylistEntry tPlaylistEntry = parsePlaylistItem(pPlaylistFile.getParentFile(), tCurrentLine);
            tPlaylist.add(tPlaylistEntry);
        }
    
        return tPlaylist;
    }


    @Override
    protected PlaylistEntry parsePlaylistItem(File pReferenceDirectory, String... pLinesToParse) {
        
        PlaylistEntry tPlaylistEntry = null;
        if (pLinesToParse != null && pLinesToParse.length == 1) {
        	
        	File tAudioFile = resolveToFile(pReferenceDirectory, pLinesToParse[0]);
        	String tArtistName = tAudioFile.getName();
            
            tPlaylistEntry = new PlaylistEntry(tAudioFile);
            tPlaylistEntry.setArtistName(tArtistName);
        }
        return tPlaylistEntry;
    }

}
